package com.ipet.app.api;


import android.support.annotation.NonNull;


import com.ipet.app.common.App;
import com.ipet.app.service.PersistentCookieStore;
import com.ipet.app.util.KLog;
import com.ipet.app.util.PreferenceManager;
import com.ipet.app.util.SerializeManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by jindongping on 16/3/8.
 */
public class RequestManager {

    private Api api;

    private OkHttpClient client;

    private static class RequestManagerHolder {
        private static RequestManager instance = new RequestManager();
    }

    public static Api getApi() {
        return RequestManagerHolder.instance.api;
    }


    private RequestManager() {
        //Cookie管理
        client = new OkHttpClient.Builder()
                .cookieJar(getCookieJar())
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.API_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
    }

    /**
     * 应用访问网络的 client
     *
     * @return OkHttpClient
     */
    public static OkHttpClient getClient() {
        return RequestManagerHolder.instance.client;
    }

    /**
     * cookie 管理
     * 访问某个host时保存cookie到 HashMap
     *
     * @return CookieJar 管理实现
     */
    @NonNull
    private CookieJar getCookieJar() {
        return new CookieJar() {

            private final PersistentCookieStore cookieStore = new PersistentCookieStore(App.getContext());

            //保存或者更新cookie到本地
            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                if (cookies != null && cookies.size() > 0) {
                    for (Cookie item : cookies) {
                        cookieStore.add(url, item);
                    }
                }
            }

            //从本地读取cookie
            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url);
                return cookies;
            }
        };
    }

}
